﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;
using Kiiro.Common.Entities;
using Kiiro.Common.Utility;
using Kiiro.SiteDefinition.ControlTemplates;
using System.Web.UI.HtmlControls;

namespace Kiiro.SiteDefinition.Core
{
    public partial class AllMainNavigationItems : BasePage
    {
        private BasePage Base
        {
            get { return ( BasePage ) Page; }
        }

        public Pager Pager
        {
            get { return ( Pager ) pager; }
        }

        private bool IsProject = false;

        private Header V2Header
        {
            get { return Base.KiiroMaster.V2Header; }
        }

        public NavigationSub NavigationSub
        {
            get { return KiiroMaster.NavigationSub; }
        }

        private List<NavigationItem> navigationItems = new List<NavigationItem> ( );
        public List<NavigationItem> NavigationItems
        {
            get { return navigationItems; }
            set { navigationItems = value; }
        }

        protected void Page_Load ( object sender, EventArgs e )
        {
            Pager.NextClick += new EventHandler ( RePopulatePage );
            Pager.PrevClick += new EventHandler ( RePopulatePage );
            Pager.EntitiesPerPageChange += new EventHandler ( RePopulatePage );

            litTitle.Text = "Kiiro Main Navigation";

            AddCommandButtons ( );

            IsProject = SPHelpers.IsProject ( SiteCollectionId, ServerRelativeUrl );

            if ( !IsPostBack )
                PopulatePage ( );
        }

        protected override void OnPreRender ( EventArgs e )
        {
            litTitleSort.Text = string.Empty;
            litTargetUrlSort.Text = string.Empty;
            litSiteLevelSort.Text = string.Empty;
            litSequenceSort.Text = string.Empty;
            litIsVisibleSort.Text = string.Empty;

            string sortIcon = string.Format ( "<img src='/_layouts/images/Kiiro/icon-sort-{0}.gif' />",
                Pager.SortDirection == SortDirection.Ascending ? "asc" : "desc" );

            if ( Pager.SortExpression == "Title" )
                litTitleSort.Text = sortIcon;
            else if ( Pager.SortExpression == "TargetUrl" )
                litTargetUrlSort.Text = sortIcon;
            else if ( Pager.SortExpression == "SiteLevel" )
                litSiteLevelSort.Text = sortIcon;
            else if ( Pager.SortExpression == "Sequence" )
                litSequenceSort.Text = sortIcon;
            else if ( Pager.SortExpression == "IsVisible" )
                litIsVisibleSort.Text = sortIcon;

            if ( IsProject )
                thSiteLevel.Visible = false;

            base.OnPreRender ( e );
        }

        public void btnCreate_Click ( object sender, EventArgs e )
        {
            Response.Redirect ( "NewForm.aspx" );
        }

        protected void btnDeleteItem_Click ( object sender, EventArgs e )
        {
            LinkButton btnDeleteItem = ( LinkButton ) sender;

            if ( btnDeleteItem != null && SPContext.Current != null && SPContext.Current.List != null )
            {
                int id = int.Parse ( btnDeleteItem.CommandArgument );
                SPContext.Current.List.Items.DeleteItemById ( id );
                Response.Redirect ( SPContext.Current.List.RootFolder.ServerRelativeUrl );
            }
        }

        public void SortBy_Click ( object sender, EventArgs e )
        {
            LinkButton link = ( LinkButton ) sender;

            if ( Pager.SortExpression != link.CommandArgument )
                Pager.SortDirection = SortDirection.Ascending;
            else
                Pager.SortDirection = Pager.SortDirection == SortDirection.Ascending ? SortDirection.Descending : SortDirection.Ascending;

            Pager.SortExpression = link.CommandArgument;

            PopulatePage ( );
        }

        protected void CustomItems_ItemDataBound ( object source, RepeaterItemEventArgs e )
        {
            try
            {
                NavigationItem item = ( NavigationItem ) e.Item.DataItem;

                // Title
                HyperLink hypDisplayItem = ( HyperLink ) e.Item.FindControl ( "hypDisplayItem" );
                if ( hypDisplayItem != null )
                {
                    hypDisplayItem.NavigateUrl = string.Format ( "DispForm.aspx?id={0}", item.Id );
                    hypDisplayItem.Text = SPHelpers.ConvertHtmlToKiiroSafeText ( item.Title );
                }

                // TargetUrl
                Label lblTargetUrl = ( Label ) e.Item.FindControl ( "lblTargetUrl" );
                if ( lblTargetUrl != null )
                    lblTargetUrl.Text = item.TargetUrl;

                // SiteLevel
                if ( IsProject )
                {
                    e.Item.FindControl ( "tdSiteLevel" ).Visible = false;
                }
                else
                {
                    Label lblSiteLevel = ( Label ) e.Item.FindControl ( "lblSiteLevel" );
                    if ( lblSiteLevel != null )
                    {
                        lblSiteLevel.Text = item.SiteLevel;
                    }
                }

                // Sequence
                Label lblSequence = ( Label ) e.Item.FindControl ( "lblSequence" );
                if ( lblSequence != null )
                    lblSequence.Text = item.Sequence.ToString ( );

                // IsVisible
                Label lblIsVisible = ( Label ) e.Item.FindControl ( "lblIsVisible" );
                if ( lblIsVisible != null )
                    lblIsVisible.Text = item.IsVisible ? "Yes" : "No";

                // Edit
                HyperLink hypEditItem = ( HyperLink ) e.Item.FindControl ( "hypEditItem" );
                if ( hypEditItem != null )
                    hypEditItem.NavigateUrl = string.Format ( "EditForm.aspx?id={0}", item.Id );

                // Delete
                LinkButton btnDeleteItem = ( LinkButton ) e.Item.FindControl ( "btnDeleteItem" );
                if ( btnDeleteItem != null )
                {
                    btnDeleteItem.CommandArgument = item.Id.ToString ( );
                    btnDeleteItem.OnClientClick = "javascript: return confirm('Are you sure you want to delete this navigation item?');";
                }

                // LastRowCssClass
                Literal litItemRowClass = ( Literal ) e.Item.FindControl ( "litItemRowClass" );
                if ( litItemRowClass != null && e.Item.ItemIndex == Pager.DisplayedCount - 1 )
                    litItemRowClass.Text = "borderless";
            }
            catch ( Exception ex )
            {
                ExceptionManagement.ExceptionManager.HandleException ( ex, false );
            }
        }

        private void AddCommandButtons ( )
        {
            if ( ContentType != null && this.Base.PermissionBitsLists [ 0 ] )
            {
                LinkButton command = new LinkButton ( );
                command.Text = "ADD NAVIGATION ITEM";
                command.Attributes.Add ( "class", "icon-add" );
                command.Click += new EventHandler ( btnCreate_Click );
                NavigationSub.Commands.Add ( command );
            }
        }

        private void PopulatePage ( )
        {
            NavigationItems = SPContext.Current.List.Items.Cast<SPListItem> ( )
                .Select ( li => new NavigationItem ( li ) ).ToList ( );

            DoSort ( );

            Pager.PopulatePager ( NavigationItems.Count, "Navigation Items" );

            rptCustomItems.DataSource = NavigationItems.GetRange ( Pager.PagingIndex, Pager.DisplayedCount );
            rptCustomItems.DataBind ( );

            if ( rptCustomItems.Items.Count == 0 )
            {
                Pager.Visible = false;
                pnlPanel.Visible = false;
            }
        }

        private void RePopulatePage ( object sender, EventArgs e )
        {
            PopulatePage ( );
        }

        private void DoSort ( )
        {
            string key = string.IsNullOrEmpty ( Pager.SortExpression ) ? "Title" : Pager.SortExpression;

            if ( key == "TargetUrl" )
                NavigationItems.Sort ( delegate ( NavigationItem x, NavigationItem y )
                {
                    return x.TargetUrl.CompareTo ( y.TargetUrl ) != 0 ?
                        x.TargetUrl.CompareTo ( y.TargetUrl ) : x.Title.CompareTo ( y.Title );
                } );
            else if ( key == "SiteLevel" )
                NavigationItems.Sort ( delegate ( NavigationItem x, NavigationItem y )
                {
                    return x.SiteLevel.CompareTo ( y.SiteLevel ) != 0 ?
                        x.SiteLevel.CompareTo ( y.SiteLevel ) : x.Title.CompareTo ( y.Title );
                } );
            else if ( key == "Sequence" )
                NavigationItems.Sort ( delegate ( NavigationItem x, NavigationItem y )
                {
                    return x.Sequence.CompareTo ( y.Sequence ) != 0 ?
                        x.Sequence.CompareTo ( y.Sequence ) : x.Title.CompareTo ( y.Title );
                } );
            else if ( key == "IsVisible" )
                NavigationItems.Sort ( delegate ( NavigationItem x, NavigationItem y )
                {
                    return x.IsVisible.CompareTo ( y.IsVisible ) != 0 ?
                        x.IsVisible.CompareTo ( y.IsVisible ) : x.Title.CompareTo ( y.Title );
                } );
            else
                NavigationItems.Sort ( delegate ( NavigationItem x, NavigationItem y )
                {
                    return x.Title.CompareTo ( y.Title );
                } );

            if ( Pager.SortDirection == SortDirection.Descending )
                NavigationItems.Reverse ( );
        }
    }
}

/*************************************************************************
 * 
 * $Log: /Internal Projects/Kiiro/Kiiro.SiteDefinition/12/TEMPLATE/FEATURES/Kiiro.Lists/MainNavigationList/AllMainNavigationItems.aspx.cs $
 * 
 * 8     2/16/10 9:29a Camerons
 * 
 * 7     2/08/10 2:28p Camerons
 * 
 * 6     1/07/10 2:40p Camerons
 * 
 * 5     1/06/10 5:35p Camerons
 * 
 * 4     1/06/10 12:39p Camerons
 * 
 * 3     4/01/10 12:03p Adamw
 * 
 * 2     21/12/09 9:31p Adamw
 * 
 * 1     17/12/09 4:10p Adamw
 * 
 ************************************************************************/